package com.qianyucc.blog.service;

import com.qianyucc.blog.mapper.*;
import com.qianyucc.blog.model.dto.*;
import com.qianyucc.blog.model.entity.*;
import com.qianyucc.blog.model.enums.*;
import com.qianyucc.blog.model.vo.*;
import org.springframework.beans.factory.annotation.*;
import org.springframework.stereotype.*;

/**
 * @author lijing
 * @date 2019-10-11 15:08
 * @description 与用户相关的业务
 */
@Service
public class UserService {
    @Autowired
    private UserMapper userMapper;

    /**
     * 普通用户码云登录
     *
     * @param userDTO 通过码云回调返回的用户信息
     * @param token   用户登录态标识
     * @return 用户信息
     */
    public UserVO giteeLogin(GiteeUserDTO userDTO, String token) {
        boolean isNewUser = false;
        UserDO userDO = userMapper.findById(userDTO.getUuid());
        if (userDO == null) {
            isNewUser = true;
            userDO = new UserDO();
            userDO.setGmtCreate(System.currentTimeMillis());
        }
        userDO.setId(userDTO.getUuid());
        userDO.setName(userDTO.getNickname());
        userDO.setLogin(userDTO.getUsername());
        userDO.setAvatarUrl(userDTO.getAvatar());
        userDO.setBio(userDTO.getRemark());
        userDO.setToken(token);
        userDO.setPlatform(Platform.GITEE.getFlag());
        userDO.setGmtUpdate(System.currentTimeMillis());
        if (isNewUser) {
            userMapper.insUser(userDO);
        } else {
            userMapper.updUser(userDO);
        }
        UserVO userVO = UserVO.create(userDO);
        return userVO;
    }

    /**
     * 普通用户登录
     *
     * @param userDTO 通过码云回调返回的用户信息
     * @param token   用户登录态标识
     * @return 用户信息
     */
    public UserVO qqLogin(QQUserDTO userDTO, String token) {
        boolean isNewUser = false;
        UserDO userDO = userMapper.findById(userDTO.getUuid());
        if (userDO == null) {
            isNewUser = true;
            userDO = new UserDO();
            userDO.setGmtCreate(System.currentTimeMillis());
        }
        userDO.setId(userDTO.getUuid());
        userDO.setName(userDTO.getNickname());
        userDO.setLogin(userDTO.getUsername());
        userDO.setAvatarUrl(userDTO.getAvatar());
        userDO.setPlatform(Platform.QQ.getFlag());
        userDO.setToken(token);
        userDO.setGmtUpdate(System.currentTimeMillis());
        if (isNewUser) {
            userMapper.insUser(userDO);
        } else {
            userMapper.updUser(userDO);
        }
        UserVO userVO = UserVO.create(userDO);
        return userVO;
    }
}
